package com.example.h5shell.utils;

import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * desc: 安卓系统文件的读写
 */
public class FileHelper {

    // 写入内部存储
    public void writeInternalFile(Context context, String fileName, String data) {
        try (FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE)) {
            fos.write(data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取内部存储
    public String readInternalFile(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();

        try (FileInputStream fis = context.openFileInput(fileName)) {
            int c;
            while ((c = fis.read()) != -1) {
                stringBuilder.append((char) c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return stringBuilder.toString();
    }

    // 写入外部存储（注意：需要权限）
    public void writeExternalFile(String filePath, String fileName, String data) {
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs(); // 创建目录
        }

        File file = new File(dir, fileName);

        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取外部存储
    public String readExternalFile(String filePath) {
        File file = new File(filePath);

        StringBuilder stringBuilder = new StringBuilder();

        try (FileInputStream fis = new FileInputStream(file)) {
            int c;
            while ((c = fis.read()) != -1) {
                stringBuilder.append((char) c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return stringBuilder.toString();
    }
}